#    GMail-Notifier - A cooler looking gmail notifier for Ubuntu
#    Copyright (C) 2009 Uday K Verma
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

from gmailnotifierimports import *
import config
import path

class NotificationManager(object):
    def __init__(self):
        if not pynotify.init ("GMail-Notifier"):
            raise Exception, "Could not initialize notification service."
        
        self.gmail_icon = "file://" + path.media_path () + "/images/gmail-icon256.png"
        self.message_cache = {}
        
        self.notify = pynotify.Notification ('GMail notifier', 'Shows status of your mailbox')
        self.notify.set_urgency (pynotify.URGENCY_NORMAL)
        
        self.messages = None
        self.currentIndex = 0
        self.presenting = False
        self.disable_notifications = False
        self.stopRequested = False
        
    def notifyMessages (self, messages):
        if self.presenting:
            return  # we are already presenting stuff to the user
        
        if not int(config.get_config ("disable-notifications")):
            self.presenting = True
        
            self.messages = self.cacheMessages (messages)
            self.currentIndex = 0
            self._showCurrent ()
        
            # setup a timer that comes up every so often and increments the counter
            #
            gobject.timeout_add (int(config.get_config('message-display-interval')),
                             self._next_message)
            
    def updateForFailed (self):
        self.notify.update ("Error retrieving mail.",
                            "There was an error trying to retrieve your e-mail.  Please check that your login credentials are correct and that your internet connection is active.",
                            self.gmail_icon)
        self.notify.show ()
        if self.presenting:
            self.stop ()
        
    def _next_message (self):
        # if the user disables notifications half way through our notification
        # process, we want to stop showing the notifications right away
        if int(config.get_config ("disable-notifications")) or self.stopRequested:
            self.presenting = False
            self.stopRequested = False
            
            return False
        else:
            self.currentIndex += 1
            if self.currentIndex >= len (self.messages):
                self.notify.close ()
                self.presenting = False
                return False
            else:
                self._showCurrent ()
            
        return True
        
    def _showCurrent (self):
        if self.messages:
            msg, snippet, auths = self.messages [self.currentIndex].title, self.messages [self.currentIndex].summary, self.messages [self.currentIndex].authors                                        
            if self.notify.update (msg,
                                   ','.join ([str(a) for a in auths]) + "\n\n" + snippet + "\n\n%d/%d" % (self.currentIndex+1, len(self.messages)),
                                   self.gmail_icon) and not int(config.get_config ("disable-notifications")):
                
                to = int(config.get_config("message-display-interval"))
                self.notify.set_timeout (to + 1000)
                self.notify.show ()
                
    def stop (self):
        self.stopRequested = True
        if self.notify:
            self.notify.close ()
            
    def cacheMessages (self, messages):
        # for each message check if we know that message, if we do, remove it,
        # if there are any messages that were not found in the messages array but we know about them
        # we forget about those messages
        #
        ret = []
        
        
        # unmark all messages
        for k in self.message_cache.keys ():
            self.message_cache [k] = False
        
        # mark all known and new messages, keeping note of the new messages
        for m in messages:
            if not self.message_cache.has_key (m.id):
                ret.append (m)
                
            self.message_cache [m.id] = True
        
        for k in self.message_cache.keys():
            if not self.message_cache [k]:
                del self.message_cache [k]
        
        return ret
    
    def clearCache (self):
        self.message_cache.clear()
        
    def close (self):
        self.notify.close ()